import $http from "@/common/util/http";
import FileSaver from "file-saver";

export function downloadPost(url, params, filename, header) {
    return $http.post(url, params, {
        headers: {'Content-Type': header ? header : 'application/x-www-form-urlencoded'},
        responseType: 'blob'
    }).then(async (data: any) => {
        const blob = new Blob([data])
        FileSaver.saveAs(blob, filename)
    }).catch((r) => {
    })
}

/**
 * 根据 blob 下载文件
 *
 * @param blob_array
 * @param fileName 文件名
 */
export const downloadBlob = (blob_array: any, fileName: any) => {
    console.log(fileName);
    let blob = new Blob([blob_array], {type: "application/force-download"});
    // window.location.href = URL.createObjectURL(blob);
    let labelA = document.createElement('a');
    labelA.href = window.URL.createObjectURL(blob);
    labelA.download = fileName;
    labelA.click();
};

export const convertBase64ToBlob = (b64Data: any) => {
    let sliceSize = 512;
    let byteCharacters = atob(b64Data.substring(b64Data.indexOf(',') + 1));
    let byteArrays = [];
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        let slice = byteCharacters.slice(offset, offset + sliceSize);
        let byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        let byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }
    return new Blob(byteArrays);
};

//  getExcel(res, name) {
//     console.log(res, name)
//     let blob = new Blob([res], {
//         type: "application/vnd.ms-excel"
//     });
//     FileSaver.saveAs(blob, name + ".xlsx");
// }

/**
 * 导出CSV文件
 * @param {*} res   文件流
 * @param {*} name  文件名
 */
// static getCsv(res, name) {
//     let blob = new Blob([res], {
//         type: "application/vnd.ms-excel"
//     });
//     FileSaver.saveAs(blob, name + ".csv");
// }

/**
 * 导出图片1
 * @param {*} url 图片地址
 * @param {*} name  文件名
 */
// static getImgURLs(url, name) {
//     let last = url.substring(url.lastIndexOf("."), url.length);
//     FileSaver.saveAs(url, `${name}${last}`);
// }
/**
 * 导出图片2
 * @param {*} res 文件流
 * @param {*} name  文件名
 */
// static downLoadImg(res, filename) {
//     let blob = new Blob([res], {
//         type: "other/jpeg"
//     });
//     FileSaver.saveAs(blob, `${filename}.jpg`);
// }

